//
//  ApplePayViewController.m
//  Molian
//
//  Created by xiaocankeji on 16/2/26.
//  Copyright © 2016年 xiaocan. All rights reserved.
//

#import "ApplePayViewController.h"
#import <IAPShare.h>
#import "FeedbackViewController.h"

@interface ApplePayViewController ()
@end

@implementation ApplePayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"会员";
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight )];
    [self.view addSubview:scrollView];
    
   // [self.navigationItem setHidesBackButton:YES animated:YES];
    
    //self.title = @"入会审核";
    self.view.backgroundColor =  APPCOLORBACKGROUNDCOLOR(1);
    CGFloat h = DeviceWidth/320*180;
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, h)];
    // v.backgroundColor = RGBA(55, 198, 119, 1);
    v.backgroundColor = RGBA(55, 149, 202, 1);
    //    v.backgroundColor = RGBA(244, 152, 68, 1);
    //    v.backgroundColor = RGBA(243, 93, 67, 1);
    [scrollView addSubview:v];
    
    UIImageView *i = [[UIImageView alloc] initWithFrame:CGRectMake(DeviceWidth/2 - 50/2, 20, 50, 50)];
    i.image = [UIImage imageNamed:@"check_icon"];
    [v addSubview:i];
    
    
    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(10, 70, DeviceWidth - 20, h - 70)];
    l.numberOfLines = 0;
    l.textColor = [UIColor whiteColor];
    l.textAlignment = NSTextAlignmentCenter;
    l.font = kFont(15);
    
    NSString *str = [Utils defaultsForKey:IAP_ID_98_YUAN];
    
    MLUser *u = [MLUser currentUser];
    
    if ((str&&[str isEqualToString:@"YES"])||u.isUserInited == 1) {
        
        l.text = @"您现在已经是会员\n不需要再次购买";
    }else{
        l.text = @"您现在还不是会员\n需要支付后才能使用该功能";
    }
    
    [v addSubview:l];
    
    CGFloat hintLabelH = 200;
    UILabel *hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0 + h, DeviceWidth - 30, hintLabelH-20)];
    
    hintLabel.textColor = RGBA(88, 88, 88, 1);
    hintLabel.textAlignment = NSTextAlignmentLeft;
    hintLabel.numberOfLines = 0;
    hintLabel.font = kFont(12);
    hintLabel.text = @"为什么收费?\n-过滤不认真人群,保证每个人都是真心交友\n-过滤约炮和猎艳人群,努力为会员提供纯净的交友环境\n-为会员提供更好使用体验,终身服务用户\n\n如何收费?\n-会员费98元\n-一次支付,终身服务\n\n恢复会员\n-已经购买成为会员的,升级或换手机设备后,点击恢复会员,可以继续使用会员功能";
    [scrollView addSubview:hintLabel];
    
    
    
    UIButton *fkBt = [UIButton buttonWithType:UIButtonTypeCustom];
    fkBt.frame = CGRectMake(DeviceWidth - 120, h+hintLabelH+10, 100, 20);
    [fkBt setTitle:@"支付遇到问题" forState:UIControlStateNormal];
    [fkBt setTitleColor:RGBA(40, 128, 193, 0.7) forState:UIControlStateNormal];
    [fkBt setTitleColor:RGBA(188, 188, 188, 1) forState:UIControlStateHighlighted];
    fkBt.titleLabel.font = kFont(12);
    [fkBt addTarget:self action:@selector(clickfkBt) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:fkBt];
    
    UILabel *payLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, h+hintLabelH+20, DeviceWidth, 30)];
    payLabel.textColor =  RGBA(45, 185 , 250, 1);
    payLabel.textAlignment = NSTextAlignmentCenter;
    payLabel.font = kFont(14);
    payLabel.text = @"会员费¥98元";
    [scrollView addSubview:payLabel];
    
    UIButton *pay = [UIButton buttonWithType:UIButtonTypeCustom];
    pay.frame = CGRectMake(30  , h+hintLabelH+20+40 , DeviceWidth - 60, 40);
    [pay setTitle:@"支付" forState:UIControlStateNormal];
    [pay setTitleColor:RGBA(255, 255, 255, 1) forState:UIControlStateNormal];
    [pay setTitleColor:RGBA(188, 188, 188, 1) forState:UIControlStateHighlighted];
    pay.titleLabel.font = kFont(15);
    pay.backgroundColor =RGBA(45, 185 , 250, 1);
    pay.layer.masksToBounds = YES;
    pay.layer.cornerRadius = 5;
    [pay addTarget:self action:@selector(clickGoPay:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:pay];
    
    UIButton *resumeBT = [UIButton buttonWithType:UIButtonTypeCustom];
    resumeBT.frame = CGRectMake(30, h+hintLabelH+20+40+50 , (DeviceWidth - 60), 40);
    [resumeBT setTitle:@"恢复会员" forState:UIControlStateNormal];
    [resumeBT setTitleColor: RGBA(45, 185 , 250, 1) forState:UIControlStateNormal];
    [resumeBT setTitleColor:RGBA(188, 188, 188, 1) forState:UIControlStateHighlighted];
    resumeBT.titleLabel.font = kFont(15);
    
//    resumeBT.backgroundColor = RGBA(40, 128, 193, 1);
    resumeBT.layer.masksToBounds = YES;
    resumeBT.layer.cornerRadius = 5;
    resumeBT.layer.borderWidth = 1;
    resumeBT.layer.borderColor =  RGBA(45, 185 , 250, 1).CGColor;
    [resumeBT addTarget:self action:@selector(clickRsumePay:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:resumeBT];
    
    
    
    UILabel *resumeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, h+hintLabelH+20+40+50+40, DeviceWidth, 30)];
    resumeLabel.textColor = RGBA(88, 88, 88, 1);
    resumeLabel.textAlignment = NSTextAlignmentCenter;
    resumeLabel.font = kFont(12);
    resumeLabel.text = @"如果已经购买会员,请点击恢复会员";
    [scrollView addSubview:resumeLabel];
    
    // 初始化IAP
    if (![IAPShare sharedHelper].iap.products) {
        [self initIAP];
    }
    CGFloat scrollViewH =h+hintLabelH+20+40+50+40+40;
    if (scrollViewH<DeviceHeight) {
        scrollViewH = DeviceHeight;
    }
  
    NSLog(@"%f",scrollViewH);
    [scrollView setContentSize:CGSizeMake(DeviceWidth, scrollViewH)];
  
   
    // Do any additional setup after loading the view.
}
- (void)clickfkBt
{
    [self.navigationController pushViewController:[[FeedbackViewController alloc]init] animated:YES];
}
// 初始化内购
- (void)initIAP {
    if(![IAPShare sharedHelper].iap) {
        NSSet *dataSet = [[NSSet alloc] initWithObjects:IAP_ID_98_YUAN, nil];
        [IAPShare sharedHelper].iap = [[IAPHelper alloc] initWithProductIdentifiers:dataSet];
        NSLog(@"%@",[IAPShare sharedHelper].iap.products);
    }
    [HUD setOnViewWithTitle:@"" animated:YES];
    
    //是否是正式
    [IAPShare sharedHelper].iap.production = YES;
    
    [[IAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest *request,SKProductsResponse *response)
     {
         [HUD hideFromViewAnimated:YES];
//         if (response > 0) {
//             
//             NSLog(@"get products succeed%@",[IAPShare sharedHelper].iap.products);
//         } else {
//             NSLog(@"get products faild");
//             [HUD Prompt:@"支付项加载失败,请退出页面再重试"];
//             
//         }
     }];
}
//检查恢复购买
- (void)clickRsumePay:(UIButton *)bt
{
    NSString *str = [Utils defaultsForKey:IAP_ID_98_YUAN];
    
    MLUser *u = [MLUser currentUser];
    
    if ((str&&[str isEqualToString:@"YES"])||u.isUserInited == 1) {
        
        [HUD Prompt:@"你已经是会员了,不需要恢复会员"];
        
        return ;
    }
    
    bt.enabled = NO;
    
    [HUD setOnViewWithTitle:nil animated:YES];
     [[IAPShare sharedHelper].iap restoreProductsWithCompletion:^(SKPaymentQueue *payment, NSError *error) {
         bt.enabled = YES;
         [HUD hideFromViewAnimated:YES];
         
         if (error == nil) {
             
             if(payment.transactions.count>0){
                 
                 for (SKPaymentTransaction *transcation in payment.transactions) {
                     
                     NSLog(@"%@",transcation.transactionIdentifier);
                     if (transcation.transactionState  ==  SKPaymentTransactionStateRestored) {
                        
                         if (transcation.payment.productIdentifier&&[transcation.payment.productIdentifier isEqualToString:IAP_ID_98_YUAN]) {
                             
                             [Utils saveToDefaults:@"YES" forKey:IAP_ID_98_YUAN];
                             [self.navigationController popViewControllerAnimated:YES];
                             [HUD Prompt:@"恢复成功"];
                         }
                         
                       //  NSLog(@"有需要恢复的交易%@",transcation.payment.productIdentifier);
                     }
                     
                     
                 }
                 
                 
             }else{
                 [HUD Prompt:@"没有可恢复的交易"];
             }
             
             
         }else{
             
             [HUD Prompt:@"连接失败"];
         }
         
         NSLog(@"%@",error);
         NSLog(@"%@",payment);
        
         
         // 将交易从交易队列中删除
       
         
     }];
    
}
//-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
//{
//    
//}
- (void)clickGoPay:(UIButton *)bt
{
 
    NSString *str = [Utils defaultsForKey:IAP_ID_98_YUAN];
    
    MLUser *u = [MLUser currentUser];
    
    if ((str&&[str isEqualToString:@"YES"])||u.isUserInited == 1) {
        
        [HUD Prompt:@"你已经是会员了,不需要再次购买"];
        
        return ;
    }
    
    
    
    if ([MobClick isJailbroken]) {
        [HUD Prompt:@"越狱设备当前不支持该方式充值"];
        return;
    }
    
    
    
    // 执行充值
    IAPHelper *iap = [IAPShare sharedHelper].iap;
    NSArray *products = iap.products;
    if (!products || [products count] == 0) {
        [HUD Prompt:@"支付项加载失败,请退出页面再重试"];
        return;
    }
    
    
//    // 找到指定的product
    NSString *identifier = IAP_ID_98_YUAN;
    SKProduct *selectProduct;
    for (SKProduct *product in products) {
        if ([product.productIdentifier isEqualToString:identifier]) {
            selectProduct = product;
            break;
        }
    }
    
    bt.userInteractionEnabled = NO;
    [HUD setOnViewWithTitle:@"正在交易..." animated:YES];
    [[IAPShare sharedHelper].iap buyProduct:selectProduct onCompletion:^(SKPaymentTransaction *transcation) {
        
        bt.userInteractionEnabled = YES;
        [HUD hideFromViewAnimated:YES];
        if (transcation.error) {
            NSLog(@"Fail %@", [transcation.error localizedDescription]);
            [HUD Prompt:@"连接失败"];
            //[self verifyPruchase];
        } else if (transcation.transactionState  ==  SKPaymentTransactionStatePurchased) {
            //[self verifyPruchase];
            [HUD setOnViewWithTitle:@"支付结果确认中" animated:YES];
            // 服务器验证支付是否成功
            NSData *transactionReceipt = [NSData dataWithContentsOfURL:[[NSBundle mainBundle] appStoreReceiptURL]];
            //NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:transactionReceipt options:1 error:nil];
            //NSLog(@"%@",dic);
            NSDictionary *verifyParams = @{
                                           @"receipt": [transactionReceipt base64EncodedStringWithOptions:0],
                                           @"rechargeMoney": @"98",
                                           @"userId": [MLUser currentUser].objectId};
            [AVCloud callFunctionInBackground:@"verifyIAPReceipt" withParameters:verifyParams block:^(id object, NSError *error) {
                [HUD hideFromViewAnimated:YES];
                if (!error) {
                    
                    [Utils saveToDefaults:@"YES" forKey:IAP_ID_98_YUAN];
                    [self.navigationController popViewControllerAnimated:YES];
//                    MLUser *u = [MLUser currentUser];
//                    u.isUserInited = 1;
//                    [u saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//                        [self.navigationController popViewControllerAnimated:YES];
//                        [HUD Prompt:@"充值成功"];
//                       
//                    }];
                    
                    
                    
                    
                    // TODO 提示充值成功
//                    // 充值成功, 刷新用户
//                    [[MLUser currentUser] refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
//                       
//                    }];
                   
                } else {
                    if ([Utils cheackConfigurationScreen]) {
                         [Utils saveToDefaults:@"YES" forKey:IAP_ID_98_YUAN];
                        [self.navigationController popViewControllerAnimated:YES];
//                        MLUser *u = [MLUser currentUser];
//                        u.isUserInited = 1;
//                        [u saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//                            
//                            [self.navigationController popViewControllerAnimated:YES];
//                            
//                            [HUD Prompt:@"充值成功"];
//                        }];
                        
                    }else{
                        [HUD Prompt:@"充值失败,请重试"];
                        NSLog(@"充值失败");
                    }
                    
                    
                }
            }];
            // 将交易从交易队列中删除
            [[SKPaymentQueue defaultQueue] finishTransaction:transcation];
        } else if (transcation.transactionState  ==  SKPaymentTransactionStateFailed) {
            [HUD Prompt:@"充值失败,请重试"];
          
        }
    }];
    
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
